using System;
using System.Text;
using System.IO;

namespace nmerge
{
    class Worker
    {
        public static Worker Current
        {
            get { return new Worker(); }
        }

        public void Execute(ArgumentParser arguments)
        {
            try
            {
                ExecuteInternal(arguments);
                Console.WriteLine("Done.");
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to merge target files: {0}", e.Message);
            }
        }

        private void ExecuteInternal(ArgumentParser arguments)
        {
            var buffer = new StringBuilder();

            foreach (var input in arguments.InputFilePathList)
            {
                Encoding target = DetectEncoding(input);
                buffer.Append(File.ReadAllText(input, target));
                buffer.AppendLine();
                buffer.AppendLine();
            }

            File.WriteAllText(arguments.OutputFilePath, buffer.ToString(), arguments.OutputFileEncoding);
        }

        private Encoding DetectEncoding(string inputFile)
        {
            using (var fs = File.OpenRead(inputFile))
            {
                if (fs.Length >= 3)
                {
                    var bom = new byte[3];
                    fs.Read(bom, 0, 3);

                    // EF BB BF -> utf-8
                    if (IsUTF8(bom))
                        return Encoding.UTF8;
                    // FE FF -> utf-16
                    if (IsUTF16(bom))
                        return Encoding.Unicode;
                }
                else if (fs.Length >= 2)
                {
                    var bom = new byte[2];
                    fs.Read(bom, 0, 2);

                    // FE FF -> utf-16
                    if (IsUTF16(bom))
                        return Encoding.Unicode;
                }

                return Encoding.GetEncoding("gb2312");
            }
        }

        private bool IsUTF16(byte[] bom)
        {
            // FE FF -> utf-16
            var UTF16_BOM = new byte[] { 0xFE, 0xFF };
            for (int i = 0; i < 2; i++)
            {
                if (UTF16_BOM[i] != bom[i])
                    return false;
            }
            return true;
        }

        private bool IsUTF8(byte[] bom)
        {
            // EF BB BF -> utf-8
            var UTF8_BOM = new byte[] { 0xEF, 0xBB, 0xBF };
            for (int i = 0; i < 3; i++)
            {
                if (UTF8_BOM[i] != bom[i])
                    return false;
            }
            return true;
        }
    }
}